package com.zbxx.web;

import com.zbxx.domain.Seckill;
import com.zbxx.dto.Exposer;

import com.zbxx.dto.SeckillExecution;
import com.zbxx.dto.SeckillResult;
import com.zbxx.enums.SeckillStatEnum;
import com.zbxx.exception.SeckillCloseException;
import com.zbxx.exception.RepeatKillException;
import com.zbxx.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Controller//@Service @Component  放入
@RequestMapping("/miaosha")// url:/模块/资源/{id}/细分 /miaosha/list
public class SeckillController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //注入serviec
    @Resource
    /*    @Resource 按照类型和名字匹配，注入service*/
    private SeckillService seckillService;

    //请求
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model) {
        //list.jsp（页面）+model（数据 ）=modelAndView
        //获取秒杀的列表页
        List<Seckill> list = seckillService.getSeckilllist();
        model.addAttribute("list", list);
        return "list";//web-inf/jsp/"list".jsp
    }

    //响应页面
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    /*@PathVariable("id") Long id表示把获取到的id的值传到形参中*/
    public String detail(@PathVariable("id") Long id, Model model) {//model用来传递数据
        if (id == null) {
            return "redirect:/miaosha/list";
            //miaosha指代的是上面的@RequestMapping("/miaosha")，list表示
            // 上面的@RequestMapping(value = "/list"，即当Id不存在是将页面重定向到List界面
        }
        Seckill seckill = seckillService.getByid(id);
        if (seckill == null) {
            return "forward:/miaosha/list";//同上
        }
        model.addAttribute("seckill", seckill);
        return "detail";
    }


    @RequestMapping(value = "/{id}/exposer", method = RequestMethod.POST,
            produces = {"application/json;charset=utf-8"})
    //输出秒杀地址
    //ajax接口 返回类型是json
    @ResponseBody
    public SeckillResult<Exposer> exposer(@PathVariable("id") Long id) {
        SeckillResult<Exposer> result;
        try {
            Exposer exposer = seckillService.exportSeckillUrl(id);
            result = new SeckillResult<Exposer>(true, exposer);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new SeckillResult<Exposer>(false, e.getMessage());
            //SeckillResult中设置了json格式， @ResponseBody的作用将返回结果变成json格式，
        }
        System.out.println("cccczzzzz"+result.isSuccess());
        return result;
    }

    @RequestMapping(value = "/{id}/{md5}/execution", method = RequestMethod.POST
            , produces = {"application/json;charset=utf-8"})
    @ResponseBody   //返回类型做ajax输出
    public SeckillResult<SeckillExecution> execute(@PathVariable("id") Long id,
                                                   @PathVariable("md5") String md5,
                                                   @CookieValue(value = "killPhone",required = false) Long phone) {

        //spring valid的验证信息
        if(phone==null){
            return new SeckillResult<SeckillExecution>(true,"未注册");
        }

        SeckillResult<SeckillExecution> result;
        try {
            SeckillExecution execution = seckillService.executeSeckill(id, phone, md5);
            return new SeckillResult<SeckillExecution>(true,execution);
            //SeckillResult中设置了json格式， @ResponseBody的作用将返回结果变成json格式，
        }catch (RepeatKillException e){
            SeckillExecution execution = new SeckillExecution(id,SeckillStatEnum.REPEAT_KILL);
                return new SeckillResult<SeckillExecution>(true,execution);
            //SeckillResult中设置了json格式， @ResponseBody的作用将返回结果变成json格式，
        }catch (SeckillCloseException e){
            SeckillExecution execution = new SeckillExecution(id,SeckillStatEnum.END);
            return new SeckillResult<SeckillExecution>(true,execution);
            //SeckillResult中设置了json格式， @ResponseBody的作用将返回结果变成json格式，
        } catch (Exception e){
            logger.error(e.getMessage(),e);
            SeckillExecution execution = new SeckillExecution(id,SeckillStatEnum.INNER_ERROR);
            return new SeckillResult<SeckillExecution>(true,execution);
            //SeckillResult中设置了json格式， @ResponseBody的作用将返回结果变成json格式，
        }
    }

    //获取系统时间
    @RequestMapping(value ="/time/now",method = RequestMethod.GET)
    @ResponseBody
    public SeckillResult<Long> Time(){
        Date now=new Date();
        return new SeckillResult(true,now.getTime());
        //SeckillResult中设置了json格式， @ResponseBody的作用将返回结果变成json格式，
    }
}
